package com.cooper.scraper;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class ResultUrl {

	private static final String URL_FUNCTION_ATTRIBUTE_NAME = "function";
	private static final String URL_ENDODE_ATTRIBUTE_NAME = "encode";
	private static final String URL_TAG = "url";

	public static List<ResultUrl> urlFactory(String xml, String encodingType)
			throws XmlPullParserException, IOException {
		List<ResultUrl> result = new ArrayList<ResultUrl>();
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser xpp = factory.newPullParser();
		xpp.setInput(new StringReader(xml));
		int eventType = xpp.getEventType();
		boolean inUrlTag = false;
		String url = null;
		String functionTagName = "";
		while (eventType != XmlPullParser.END_DOCUMENT) {
			if (eventType == XmlPullParser.START_TAG) {
				if (URL_TAG.equals(xpp.getName())) {
					inUrlTag = true;
					functionTagName = xpp.getAttributeValue(null,
							URL_FUNCTION_ATTRIBUTE_NAME);
					if ((encodingType == null) || "".equals(encodingType)) {
						encodingType = xpp.getAttributeValue(null,
								URL_ENDODE_ATTRIBUTE_NAME);
					}
				}
			} else if (eventType == XmlPullParser.TEXT) {
				if (inUrlTag) {
					url = xpp.getText();
				}
			} else if (eventType == XmlPullParser.END_TAG) {
				if (URL_TAG.equals(xpp.getName())) {
					inUrlTag = false;
					result.add(new ResultUrl(url, functionTagName, encodingType));
				}
			}
			eventType = xpp.next();
		}
		return result;
	}

	public ResultUrl() {
		super();
	}

	public ResultUrl(String url, String function, String encodingType) {
		super();
		this.url = url;
		this.function = function;
		this.encodingType = encodingType;
	}

	private String url;
	private String function;
	private String encodingType;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getFunction() {
		return function;
	}

	public void setFunction(String function) {
		this.function = function;
	}

	public String getEncodingType() {
		return encodingType;
	}

	public void setEncodingType(String encodingType) {
		this.encodingType = encodingType;
	}

}
